<script src="../../../api/remote-search.js"></script>
<template>
  <div class="tableOperate hey-table-operate">
    <div style="margin: 5px 0">{{ tableTitle }}</div>

    <!-- 列表按钮 -->
    <div v-show="!btnHide" class="hey-toolbar-container">
      <el-button
        v-if="showScroll"
        class="left-btn ctrl-btn"
        size="mini"
        type="primary"
        icon="el-icon-d-arrow-left"
        @click="scrollLeft"
      />
      <div ref="wrap" class="hey-toolbar-wrap" :style="wrapStyle">
        <div ref="toolbar" class="hey-toolbar">
          <hey-table-el-button
            v-for="item in showedBtnGroup"
            :key="item.name"
            class="hey-toolbar-button"
            :item="item"
            :operate-param="operateParam"
            :pagination="pagination"
            :table-data="tableData"
            :selected="selected"
            :columns="columns"
            @showLoading="showLoading"
            @reqData="reqData"
          />
        </div>
      </div>
      <el-button
        v-if="showScroll"
        class="right-btn ctrl-btn"
        size="mini"
        type="primary"
        icon="el-icon-d-arrow-right"
        @click="scrollRight"
      />
    </div>
    <!--列表-->
    <el-row>
      <el-table
        ref="elTable"
        v-loading="loading"
        :max-height="tableHeight"
        :show-header="showHeader"
        :empty-text="emptyText"
        border
        stripe
        fit
        :data="tableData"
        :cell-style="cellStyle"
        highlight-current-row
        :class="[singleSelect ? 'hey-single-table' : '']"
        :row-class-name="tableRowClassName"
        lazy
        :load="load"
        :row-key="rowKey"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @select="handleSelect"
        @row-dblclick="handleRowDbclick"
      >
        <el-table-column
          v-if="isSelect"
          :selectable="selectable"
          type="selection"
          width="55"
          header-align="center"
          align="center"
        />
        <el-table-column v-if="isRadio" label="" width="55">
          <template scope="scope">
            <el-radio v-model="radio" :label="scope.$index" @change.native="getCurrentRow(scope.$index,scope.row)">&nbsp</el-radio>
          </template>
        </el-table-column>
        <el-table-column
          v-if="indexRow"
          label="序号"
          type="index"
          width="55"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            {{ (pagination.pageNum-1)*pagination.pageSize+scope.$index+1 }}
          </template>
        </el-table-column>
        <template v-for="(tabCol, index) in tabColumns">
          <template v-if="tabCol.link">
            <el-table-column
              :key="index"
              :label="tabCol.title"
              :prop="tabCol.key"
              :sortable="tabCol.isSort"
              :width="tabCol.width"
              header-align="center"
              align="center"
            >
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row[tabCol.key + '_over']" class="item" effect="dark" :content="scope.row[tabCol.key]" placement="top">
                  <span v-if="scope.row[tabCol.key + '_over']" class="hey-link-text haha" v-html="tabCol.formatter ? tabCol.formatter(scope.row,scope.column,scope.row[tabCol.key]) : scope.row[tabCol.key]" />
                </el-tooltip>
                <span v-else class="hey-link-text" v-html="tabCol.formatter ? tabCol.formatter(scope.row,scope.column,scope.row[tabCol.key]) : scope.row[tabCol.key]" /><el-link v-if="tabCol.show ? tabCol.show(scope.row,tabCol.key) : true" type="primary" :icon="tabCol.link" @click="tabCol.click(scope.row,tabCol.key)" />
              </template>
            </el-table-column>
          </template>
          <template v-else-if="tabCol.udf">
            <el-table-column
              :key="index"
              :label="tabCol.title"
              :prop="tabCol.key"
              header-align="center"
              align="center"
            >
              <!--eslint-disable-next-line-->
              <template slot-scope="scope">
                <span v-if="tabCol.formatter" :imgUrl="tabCol.formatter(scope.row,scope.column,scope.row[tabCol.key])" />
                <hey-image v-if="scope.row[tabCol.key]" class="hey-table-image" :img-url="scope.row[tabCol.key]" :large-url="scope.row.largeUrl" :group="scope.row.group" />
              </template>
            </el-table-column>
          </template>
          <template v-else-if="tabCol.toolTip">
            <el-table-column
              :key="index"
              :label="tabCol.title"
              :prop="tabCol.key"
              header-align="center"
              align="center"
            >
              <!--eslint-disable-next-line-->
              <template slot-scope="scope">
                <!--<span v-if="tabCol.formatter" :imgUrl="tabCol.formatter(scope.row,scope.column,scope.row[tabCol.key])" />-->
                <el-popover
                  placement="bottom"
                  width="280"
                  trigger="hover"
                  popper-class="table-pop"
                >
                  <div v-if="tabCol.formatter" v-html="tabCol.formatter(scope.row,scope.column,scope.row[tabCol.key])" />
                  <span slot="reference" class="text pointer">{{ scope.row[tabCol.key] }}</span>
                </el-popover>
              </template>
            </el-table-column>
          </template>
          <template v-else-if="tabCol.btnCol">
            <el-table-column
              :key="index"
              :label="tabCol.title"
              :prop="tabCol.key"
              :sortable="tabCol.isSort"
              :show-overflow-tooltip="true"
              :width="tabCol.width"
              header-align="center"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="tabCol.click(scope.row,tabCol.key)">
                  {{ scope.row[tabCol.key] }}
                </el-button>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <hey-table-column
              :key="index"
              :label="tabCol.title"
              :prop="tabCol.key"
              :sortable="tabCol.isSort"
              :formatter="tabCol.formatter"
              :show-overflow-tooltip="tabCol.showOverflowTooltip"
              :width="tabCol.width"
              :clcd="tabCol.clcd"
              :date="tabCol.date"
              :time="tabCol.time"
              :money="tabCol.money"
            />
          </template>
        </template>
        <template v-if="$slots.tools">
          <slot name="tools" />
        </template>
      </el-table>
    </el-row>
    <el-row v-if="hasPagination" class="pagination" type="flex" justify="end">
      <el-pagination
        :current-page.sync="pagination.pageNum"
        :page-sizes="pageSizes"
        :page-size.sync="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="reqData"
        @current-change="reqData"
      />
    </el-row>
    <el-row v-if="!hasPagination" class="pagination" type="flex" justify="end">
      <span class="el-pagination__total">共&nbsp;{{ total }}&nbsp;条</span>
    </el-row>
  </div>
</template>

<script>
import utils from '@/utils/utils'
import heyTableElButton from './components/hey-table-el-button'
export default {
  name: 'HeyTable',
  components: {
    heyTableElButton,
    heyTableColumn: () => import('@/components/hey/hey-table/components/hey-table-column')
  },
  mixins: [utils],
  props: {
    emptyText: {
      type: String,
      default: ''
    },
    isSelect: { // 是否显示多选框
      default: false,
      type: Boolean
    },
    autoWidth: { // 自适应列表宽度
      default: true,
      type: Boolean
    },
    isRadio: { // 是否显示单选框
      default: false,
      type: Boolean
    },
    isTogetherChoose: { // 是否连带选中
      default: true,
      type: Boolean
    },
    indexRow: { // 是否显示序号
      default: true,
      type: Boolean
    },
    showHeader:{ // 是否显示列头
      default: true,
      type: Boolean
    },
    btnHide: {// 是否显示按钮组
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    columns: Array,
    btnGroup: {
      type: Array,
      default: () => {
        return []
      }
    },
    selectChangeUpdate: {
      type: Boolean,
      default: false
    },
    operateParam: Object,
    tableTitle: String,
    hasPagination: {
      type: Boolean,
      default: true
    },
    pagination: {
      type: Object,
      default: () => {
        return {
          pageNum: 1, // 多页查询跳转页码
          pageSize: 10 // 多页查询每页笔数
        }
      }
    },
    pageSizes: {
      type: Array,
      default: () => [10, 20, 50, 100]
    },
    selectable: {
      type: Function,
      default: () => () => true
    },
    singleSelect: {
      type: Boolean,
      default: false
    },
    rowKey: String,
    lazy: {
      type: Boolean,
      default: false
    },
    load: {
      type: Function,
      default: () => () => {
      }
    },
    chooseData:{
      type:Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      tabColumns:[],
      radio:false,
      rowIndex: '', // 选中第几行
      selected: [], // 选中行
      selectedRow: {}, // 选中数据
      tableHeight: 600,
      formOptions: {
        labelWidth: '80px',
        labelPosition: 'left',
        saveLoading: false
      },
      showScroll: false,
      wrapStyle: {},
      loading: false,
      queryParam: {},
      transId: '',
      grp: '',
      total: 0,
      autoSelect: false
    }
  },
  computed: {
    showedBtnGroup() {
      return this.btnGroup.filter(item => item.show === true)
    },
    // tabColumns() {
    //   const columns = this.columns.filter(item => item.hidden !== true)
    //   if(this.autoWidth){
    //     for(let i=0;i<columns.length;i++){
    //       var str = columns[i].title
    //       columns[i].width = (this.getTextWidth(str)+50).toString()
    //     }
    //   }
    //   return columns
    // },
    totalRec: function() {
      return 1
    },
    confIndexArr() {
      const { tableData } = this
      if (this.isNull(tableData) || this.isNull(this.columns.find(item => ['last_chk_stcd', 'chk_stcd'].includes(item.key)))) {
        return []
      }
      const arr = tableData.map((item, index) => {
        if (item.last_chk_stcd || item.chk_stcd) {
          if (item.last_chk_stcd === '1' || item.chk_stcd === '1') {
            return index
          }
        }
      })
      return arr
    }
  },
  async created() {
  },
  mounted() {
    this.$elTable = this.$refs.elTable
    this.getTabColumnsWidth()
    this.$emit('inited')
    /*window.onresize = () => {
      this.resizeToolbar()
    }
    this.$nextTick(() => {
      this.resizeToolbar()
    })*/
  },
  beforeDestroy() {
    this.removeHeyResize()
  },
  methods: {
    getTabColumnsWidth() {
      const columns = this.columns.filter(item => item.hidden !== true)
      if(this.autoWidth){
        for(let i=0;i<columns.length;i++){
          var str = columns[i].title
          columns[i].width = (this.getTextWidth(str)+70).toString()
        }
      }
      this.tabColumns=columns
    },
    getCurrentRow(index,row){
      this.selectedRow = row
    },
    removeHeyResize() {
      const eventName = this._uid
      const heyResizeList = window.heyResizeList || []
      heyResizeList.splice(heyResizeList.findIndex(item => item.eventName === eventName), 1)
    },
    cellStyle({row, column, rowIndex, columnIndex}){
      if(row.rmrk){
        return "background-color:#"+row.rmrk+"!important"
      }else{
        return null
      }
    },
    async cacheClcd() {
      for (const clcd of this.columns.reduce((pre, { clcd }) => {
        if (clcd) {
          pre.add(clcd)
        }
        return pre
      }, new Set())) {
        await this.getOptions(clcd)
      }
    },
    showColumns(keys = [], flag = false) {
      this.columns.forEach(item => {
        if (keys.includes(item.key)) {
          this.$set(item, 'hidden', flag)
        }
      })
    },
    hideColumns(keys = []) {
      this.showColumns(keys, true)
    },
    /**
             * @param {String} transId
             * @param {Object} param
             * @param {String} grp
             * @param {}
             * @returns {Promise<void>}
             */
    async query(transId, param, grp, flag = true) {
      if(this.hasPagination){
        if (!this.transId || flag === false) {
          param = this.cloneDeep(param)
          this.queryParam = param
          this.transId = transId
          this.grp = grp
          Object.assign(this.pagination, {
            pageNum: 1
          })
        }
        return await this.reqData()
      }else{
        this.loading = true
        await this.cacheClcd()
        await this.get(transId, param).then(res => {
          this.tableData.splice(0, this.tableData.length, ...res)
          this.total = res.length
        }).catch(err=>{
          this.tableData.splice(0, this.tableData.length)
        })
        this.loading = false
      }
    },
    async reqData() {
      await this.cacheClcd()
      if(this.isRadio){
        this.radio = false
      }
      const { transId, queryParam, pagination, grp } = this
      this.loading = true
      this.clearData()

      await this.getPage(transId, queryParam, pagination.pageNum, pagination.pageSize, {
        showLoading: false
      }).then(ret => {
        const response = ret
        ret = ret[grp] || ret
        const grpData = ret.list
        if (Array.isArray(grpData)) {
          this.tableData.splice(0, this.tableData.length, ...grpData)
        } else {
          this.tableData.splice(0, this.tableData.length)
        }
        this.total = ret.total || 0
        this.total *= 1
        pagination.pageSize = ret.pageSize
        pagination.pageNum = ret.pageNum
        this.$emit('on-load-success', response)
      }).catch(err => {
        console.log('err', err)
        this.tableData.splice(0, this.tableData.length)
        this.total = 0
      })
      this.loading = false
      return this.tableData
    },
    scrollLeft() {
      this.$refs.wrap.scrollLeft -= 200
    },
    scrollRight() {
      this.$refs.wrap.scrollLeft += 200
    },
    handleSelect(selection, row) {
      this.selectedRow = row
    },
    clearData() {
      this.autoSelect = false
      this.selectedRow = {}
      this.selected = []
      // this.total = 0
      this.tableData.splice(0, this.tableData.length)
    },
    handleSelectionChange(selection) {
      if (this.autoSelect) {
        return
      }
      setTimeout(() => {
        this.selected = selection
        const row = this.selectedRow
        if (this.singleSelect) {
          this.autoSelect = true
          this.$elTable.clearSelection()
          if (selection.length) {
            if(this.isTogetherChoose){
              this.$elTable.toggleRowSelection(row)
            }
            this.selected = [row]
          }
          setTimeout(() => {
            this.autoSelect = false
          }, 0)
        }
        this.$emit('select', this.selected, row, this.selected.find(item => item === row) !== undefined)
        this.$emit('selection-change', this.selected)
      }, 0)
    },
    handleRowDbclick(row, event) {
      this.$emit('row-dblclick', row)
    },
    handleRowClick(row, column, event) {
      const canSelect = this.selectable(row)
      if (canSelect) {
        this.selectedRow = row
        if(this.isRadio){
          let index = this.tableData.findIndex(
            item => item === this.selectedRow
          )
          if (index > -1) {
            this.radio = index
          }
        }else{
          if(this.isTogetherChoose){
            this.$refs.elTable.toggleRowSelection(row)
          }
        }
      }
      this.$emit('row-click', row, event, column)
    },
    resizeToolbar() {
      const { wrap, toolbar } = this.$refs
      let showScroll, wrapStyle
      if (!wrap || !toolbar) {
        return
      }
      if (wrap.scrollWidth > toolbar.offsetWidth) {
        showScroll = true
        wrapStyle = {
          overflow: 'hidden',
          margin: '0 6px'
        }
      } else {
        showScroll = false
        wrapStyle = {
          overflow: 'auto',
          margin: '0'
        }
      }
      this.wrapStyle = wrapStyle
      this.showScroll = showScroll
    },
    showLoading(flag) {
      this.loading = flag
    },
    /**
     * 遍历列的所有内容，获取最宽一列的宽度
     * @param arr
     */
    getMaxLength (arr) {
      return arr.reduce((acc, item) => {
        if (item) {
          let calcLen = this.getTextWidth(item)
          if (acc < calcLen) {
            acc = calcLen
          }
        }
        return acc
      }, 0)
    },
    /**
     * 使用span标签包裹内容，然后计算span的宽度 width： px
     * @param valArr
     */
    getTextWidth(str) {
      let width = 0;
      let html = document.createElement('span');
      html.innerText = str;
      html.className = 'getTextWidth';
      document.querySelector('body').appendChild(html);
      width = document.querySelector('.getTextWidth').offsetWidth;
      document.querySelector('.getTextWidth').remove();
      return width;
    },
    tableRowClassName({ row, rowIndex }) {

    },
  },
  watch: {
    /**
     * 监控表格的数据data，自动设置表格宽度
     * @param valArr
     */
    tableData(valArr) {
      if(this.autoWidth){
        const _this = this
        this.tabColumns = this.tabColumns.map(function (value) {
          const arr = valArr.map(x => x[value.key])  // 获取每一列的所有数据
          arr.push(value.title)  // 把每列的表头也加进去算
          if(_this.getMaxLength(arr) + 70 > 360){
            value.width = '360'
          }else{
            value.width = (_this.getMaxLength(arr) + 70).toString() // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
          }
          return value
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .pagination {
    margin-top: 10px;
  }
  .link-text {
    margin-right: 4px;
  }
    .hey-toolbar-container {
        display: flex;
        align-items: center;

        .el-button.ctrl-btn {
            padding-left: 0;
            padding-right: 0;
            margin-bottom: 5px;
        }

        .hey-toolbar-wrap {
            white-space: nowrap;
            overflow: auto;

            .el-button--primary.is-plain {
                color: #409EFF;
                background: #ecf5ff;
                border-color: #b3d8ff;
            }

            .el-button--primary.is-plain:focus, .el-button--primary.is-plain:hover {
                background: #409EFF;
                border-color: #409EFF;
                color: #fff;
            }

            .hey-toolbar-button {
                margin-left: 10px;
            }

            .hey-toolbar-button:first-child {
                margin-left: 0;
            }

            .el-button.is-disabled.is-plain, .el-button.is-disabled.is-plain:focus, .el-button.is-disabled.is-plain:hover {
                background-color: #ebeef5;
                border-color: #ebeef5;
                color: #c0c4cc;
            }
        }
    }
</style>
<style lang="scss">
  .table-pop {
    padding: 15px;
    line-height: 1.6;
    background: #F5F7FA;
    .popper__arrow::after {
      border-bottom-color: #F5F7FA!important;
    }
    .tip-item {
      display: flex;
      .label {
      }
      .text {
        flex: 1;
      }
    }
  }
  .el-tooltip__popper{
    max-width: 80% !important;
  }
  .hey-link-text {
    margin-right: 4px;
  }
    .hey-table-operate .el-table__body-wrapper, .hey-table-operate .el-table {
    }
    .hey-table-image {
      display: inline-block;
      height: 50px;
      width: 50px;
      img {
        max-height: 100%;
        max-width: 100%;
      }
    }
</style>
